package com.zhang.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.conditions.update.UpdateWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.mysql.jdbc.StringUtils;
import com.zhang.mapper.IInputInfoMapper;
import com.zhang.mapper.IInputOrderMapper;
import com.zhang.pojo.InputCarBean;
import com.zhang.pojo.InputInfoAndOrder;
import com.zhang.pojo.InputInfoBean;
import com.zhang.pojo.InputOrderBean;
import com.zhang.service.IInputInfoService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.time.LocalDate;
import java.util.ArrayList;
import java.util.List;

@Service
public class InputInfoServiceImpl implements IInputInfoService {

    @Autowired
    private IInputInfoMapper inputInfoMapper;
    @Autowired
    private IInputOrderMapper inputOrderMapper;

    @Override
    public IPage<InputInfoBean> findByItem(Page<InputInfoBean> page, String name, LocalDate start, LocalDate end) {
        UpdateWrapper<InputInfoBean> wrapper = new UpdateWrapper<>();
        if (!StringUtils.isNullOrEmpty(name)){
            wrapper.like("ii_name",name);
        }if (start != null){
            wrapper.ge("ii_time",start);
        }if (end != null){
            wrapper.le("ii_time",end);
        }
        return inputInfoMapper.selectPage(page,wrapper);
    }

    @Override
    public InputInfoAndOrder findById(int id) {
        InputInfoAndOrder andOrder = new InputInfoAndOrder();
        InputInfoBean inputInfoBean = inputInfoMapper.selectById(id);
        QueryWrapper<InputOrderBean> wrapper = new QueryWrapper<>();
        wrapper.eq("fk_inputInfoId",id);
        List<InputOrderBean> inputOrderBeans = inputOrderMapper.selectList(wrapper);
        andOrder.setInputInfoBean(inputInfoBean);
        andOrder.setInputOrderBeans(inputOrderBeans);
        return andOrder;
    }

    @Override
    public void add(InputInfoBean inputInfoBean, List<InputCarBean> inputCarBeans) {
        inputInfoMapper.add(inputInfoBean);
        List<InputOrderBean> inputOrderBeans = new ArrayList<>();
        for (InputCarBean inputCarBean : inputCarBeans) {
            InputOrderBean inputOrderBean = new InputOrderBean();
            inputOrderBean.setName(inputCarBean.getName());
            inputOrderBean.setMill(inputCarBean.getMill());
            inputOrderBean.setPurchase(inputCarBean.getPurchase());
            inputOrderBean.setSale(inputCarBean.getSale());
            inputOrderBean.setCount(inputCarBean.getCount());
            inputOrderBean.setInputInfoId(inputInfoBean.getId());
            inputOrderBeans.add(inputOrderBean);
        }
        for (int i = 0; i < inputOrderBeans.size(); i++) {
            inputOrderMapper.insert(inputOrderBeans.get(i));
        }
    }
}
